# Create your views here.

from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django import forms
from django.db.models import Q  #For using OR in filter
from django.core.exceptions import ValidationError

import HeaderAnalyzer.models as m
import functionsPA as f
from forms import NewURL
from datetime import datetime
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

#Handle slash
def handleSlash(s):
	if s.endswith('/'):
	  s = s[:-1]
	else:
		s += '/'
	return s

# Check if query set is not empty for a query
def first(query):  
	try:  
	  return query.all()[0]  
	except:  
		return None  

# Handles url.html
def home(request):
	if request.method == 'POST':
		form = NewURL(request.POST)
		if form.is_valid():
			urlField = form.cleaned_data['url']

			urlTotalSize = first(m.View_Total_Size.objects.filter(Q(url=urlField) | Q(url=handleSlash(urlField))))
						
			if not urlTotalSize:
				# URL not present -> Call URL Profile Builder
				# Call Praveen/Deepa's function
				return render(request, 'Results.html', { 'status' : 'Not Present' })

			
			# Get Details
			urlSummary = m.View_Summary.objects.filter(Q(url=urlField) | Q(url=handleSlash(urlField)))			
			
			return render(request, 'Results.html', { 'status' : 'Present', 'urlTotal' : urlTotalSize, 'urlSum' : urlSummary });
	else:
		form = NewURL()

	return render(request, 'url.html', {
		'form': form,
	})
	# if 

# Opens thanks.html
def thanks(request):
	return render_to_response('thanks.html')
	

